<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useBoolean } from '@sa/hooks';
import TableHeaderOperation from '@/components/advanced/table-header-operation.vue';
import { fetchAllHolidays } from '@/service/api/holiday';
import CurrencySearch from './modules/currency-search.vue';
import CurrencyHolidayModal from './modules/currency-holiday-modal.vue';
import AddCurrencyModal from './modules/add-currency-modal.vue';
import ViewHolidayModal from './modules/view-holiday-modal.vue';

defineOptions({
  name: 'HolidayManage'
});

// 货币信息接口
interface CurrencyInfo {
  currencyCode: string;
  holidayCount: number;
  lastUpdateTime?: string;
}

const loading = ref(false);
const { bool: modalVisible, setTrue: openModal, setFalse: closeModal } = useBoolean();
const { bool: addModalVisible, setTrue: openAddModal, setFalse: closeAddModal } = useBoolean();
const { bool: viewModalVisible, setTrue: openViewModal, setFalse: closeViewModal } = useBoolean();

const searchModel = reactive({
  currencyCode: ''
});

const currencyData = ref<CurrencyInfo[]>([]);
const selectedRowKeys = ref<string[]>([]);
const selectedCurrency = ref<string>('');
const viewCurrency = ref<string>('');

const columns = [
  {
    key: 'index',
    title: '序号',
    align: 'center' as const,
    width: 64,
    customRender: ({ index }: { index: number }) => index + 1
  },
  {
    key: 'currencyCode',
    title: '货币代码',
    dataIndex: 'currencyCode',
    align: 'center' as const,
    width: 120
  },
  {
    key: 'holidayCount',
    title: '假日数量',
    dataIndex: 'holidayCount',
    align: 'center' as const,
    width: 100
  },
  {
    key: 'lastUpdateTime',
    title: '最后更新时间',
    dataIndex: 'lastUpdateTime',
    align: 'center' as const,
    width: 180
  },
  {
    key: 'operate',
    title: '操作',
    align: 'center' as const,
    width: 200,
    customRender: ({ record }: { record: CurrencyInfo }) => {
      return [
        {
          type: 'primary',
          ghost: true,
          size: 'small',
          onClick: () => handleViewHolidays(record.currencyCode),
          children: '查看假日'
        }
      ];
    }
  }
];

const columnChecks = ref(
  columns.map((col, index) => ({
    key: `col-${index}`,
    title: col.title,
    checked: true
  }))
);

const rowSelection = {
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[]) => {
    selectedRowKeys.value = keys.map(String);
  }
};

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    getCurrencyData();
  },
  onShowSizeChange: (_current: number, size: number) => {
    pagination.current = 1;
    pagination.pageSize = size;
    getCurrencyData();
  }
});

async function getCurrencyData() {
  loading.value = true;
  try {
    const { data: resData, error } = await fetchAllHolidays();
    if (resData) {
      // 按货币代码分组统计假日数量
      const currencyMap = new Map<string, number>();
      resData.forEach(holiday => {
        const count = currencyMap.get(holiday.currencyCode) || 0;
        currencyMap.set(holiday.currencyCode, count + 1);
      });

      // 转换为货币信息数组
      const allCurrencyData: CurrencyInfo[] = Array.from(currencyMap.entries()).map(([currencyCode, holidayCount]) => ({
        currencyCode,
        holidayCount,
        lastUpdateTime: new Date().toLocaleString()
      }));

      // 设置总数
      pagination.total = allCurrencyData.length;

      // 分页处理
      const startIndex = (pagination.current - 1) * pagination.pageSize;
      const endIndex = startIndex + pagination.pageSize;
      currencyData.value = allCurrencyData.slice(startIndex, endIndex);
    } else {
      console.error('获取假日数据失败:', error);
      currencyData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
}

function handleViewHolidays(currencyCode: string) {
  selectedCurrency.value = currencyCode;
  openModal();
}

function handleViewHolidaysReadonly(currencyCode: string) {
  viewCurrency.value = currencyCode;
  openViewModal();
}

function handleSearch() {
  console.log('搜索:', searchModel);
  getCurrencyData();
}

function handleReset() {
  Object.assign(searchModel, {
    currencyCode: ''
  });
  getCurrencyData();
}

function handleAdd() {
  openAddModal();
}

function onModalClose() {
  closeModal();
  getCurrencyData(); // 刷新数据
}

function onAddModalClose() {
  closeAddModal();
  getCurrencyData(); // 刷新数据
}

function onViewModalClose() {
  closeViewModal();
}

onMounted(() => {
  getCurrencyData();
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CurrencySearch v-model:model="searchModel" @reset="handleReset" @search="handleSearch" />
    <ACard title="货币假日管理" :bordered="false" size="small" class="flex-1 card-wrapper">
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="selectedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getCurrencyData"
        />
      </template>
      <ATable
        :columns="columns"
        :data-source="currencyData"
        size="small"
        :scroll="{ x: 'max-content' }"
        :loading="loading"
        :row-selection="rowSelection"
        :pagination="pagination"
        row-key="currencyCode"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operate'">
            <ASpace>
              <AButton type="primary" ghost size="small" @click="handleViewHolidaysReadonly(record.currencyCode)">
                查看假日
              </AButton>
              <AButton type="primary" ghost size="small" @click="handleViewHolidays(record.currencyCode)">
                修改假日
              </AButton>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>
    <CurrencyHolidayModal v-model:open="modalVisible" :currency-code="selectedCurrency" @close="onModalClose" />
    <AddCurrencyModal v-model:open="addModalVisible" @close="onAddModalClose" />
    <ViewHolidayModal v-model:open="viewModalVisible" :currency-code="viewCurrency" @close="onViewModalClose" />
  </div>
</template>

<style scoped>
.card-wrapper {
  height: 100%;
}

.ant-table-wrapper {
  min-height: 400px;
  height: auto;
}
</style>
